package com.yami.shop.platform.task;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yami.shop.mystery.common.service.ActivityPresellQualificationServer;
import com.yami.shop.rights.common.model.ProdRights;
import com.yami.shop.rights.common.model.RightsTransferRecord;
import com.yami.shop.rights.common.service.ProdRightsService;
import com.yami.shop.rights.common.service.RightsTransferRecordService;
import com.yami.shop.rights.common.strategy.PersonRightsFactory;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Slf4j
@Component
@AllArgsConstructor
public class RightsTask {

    @Autowired
    private ProdRightsService prodRightsService;
    @Autowired
    private PersonRightsFactory personRightsFactory;
    @Autowired
    private RightsTransferRecordService rightsTransferRecordService;

    // 权益过期处理
    @XxlJob("RightsEffectiveTask")
    public void startAssetTransfer() {
        // 查询过期权益信息
        QueryWrapper<ProdRights> prodRightsQueryWrapper = new QueryWrapper<>();
        prodRightsQueryWrapper.lt("exchange_end_time",new Date());
        prodRightsQueryWrapper.isNotNull("exchange_end_time");
        prodRightsQueryWrapper.eq("status",1);
        List<ProdRights> list = prodRightsService.list(prodRightsQueryWrapper);
        if(ObjectUtil.isEmpty(list)){
            return;
        }
        // 修改权益主表为过期
        list.forEach(s->s.setStatus(3L));
        prodRightsService.updateBatchById(list);
        personRightsFactory.updateRightsEffective(list);

    }

    /**
     * 未领取的权益转赠处理
     */
    @XxlJob("transferRightsExpireTask")
    public void transferRightsExpire(){
        // 查询过期的权益转移记录
        QueryWrapper<RightsTransferRecord> rightsTransferRecordQueryWrapper = new QueryWrapper<>();
        rightsTransferRecordQueryWrapper.eq("status","1");
        rightsTransferRecordQueryWrapper.lt("create_time", DateUtil.offsetDay(new Date(),-1));
        List<RightsTransferRecord> list = rightsTransferRecordService.list(rightsTransferRecordQueryWrapper);
        if(ObjectUtil.isEmpty(list)){
            return;
        }
        list.forEach(s->s.setStatus(4));
        rightsTransferRecordService.updateBatchById(list);
    }

}
